<template>
  <div class="submit">
    <el-form ref="dataForm" :rules="rules" :model="form">
      <el-col :xs="20" :sm="22" :md="22" :lg="22" :xl="22">
        <el-form-item prop="content">
          <el-input v-model="form.content" :autosize="{ minRows: 1, maxRows: 4 }" type="textarea" placeholder="support markdown" />
        </el-form-item>
      </el-col>
      <el-col :xs="4" :sm="2" :md="2" :lg="2" :xl="2">
        <el-form-item class="save">
          <el-button v-loading="loading" type="text" class="el-icon-check" @click="submitForm">save</el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { createTopicSnippet } from '@/api/info/topic-snippet'

const defaultForm = {
  content: '',
  topicId: 0,
  uid: 0
}

export default {
  name: 'CreateSnippet',
  data() {
    return {
      form: {},
      rules: {
        content: [{ required: true, message: ' ', trigger: 'blur' }]
      },
      loading: false
    }
  },
  computed: {
    ...mapGetters(['uid'])
  },
  created() {
    const topicId = this.$route.params.id
    this.form = Object.assign({}, defaultForm, { topicId: topicId }, { uid: this.uid })
  },
  methods: {
    submitForm() {
      console.log(this.form)
      debugger
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          this.loading = true
          createTopicSnippet(this.form)
            .then(response => {
              // 向父组件返回数据
              this.$emit('create', response.result)
              this.$notify({
                title: 'Success',
                message: 'save successfully',
                type: 'success',
                duration: 2000
              })
              this.reset()
            })
            .catch(() => {
              this.loading = false
            })
          this.loading = false
        }
      })
    },
    reset() {
      this.$refs['dataForm'].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.submit {
  padding: 5px;
  .save {
    text-align: center;
    float: right;
    font-size: 20px;
  }
}
</style>
